package top.jacktgq.itheima.netty.protocol_design.groupchat.rpc;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.util.concurrent.DefaultPromise;
import lombok.extern.slf4j.Slf4j;
import top.jacktgq.itheima.netty.protocol_design.groupchat.message.RpcRequestMessage;
import top.jacktgq.itheima.netty.protocol_design.groupchat.protocol.MessageCodecSharable;
import top.jacktgq.itheima.netty.protocol_design.groupchat.protocol.ProtocolFrameDecoder;
import top.jacktgq.itheima.netty.protocol_design.groupchat.server.service.HelloService;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @Author CandyWall
 * @Date 2021/3/23--14:49
 * @Description
 */
@Slf4j
public class RpcClientMgr {
    public static void main(String[] args) {
        /*RpcRequestMessage message = new RpcRequestMessage(
                1,
                "top.jacktgq.itheima.netty.protocol_design.groupchat.server.service.HelloService",
                "sayHello",
                String.class,
                new Class[] {String.class},
                new Object[]{"张三"}
        );
        getChannel().writeAndFlush(message);*/
        HelloService helloService = getProxyService(HelloService.class);
        System.out.println(helloService.sayHello("张三"));
    }

    /**
     * 创建代理类执行RPC调用，屏蔽一些复杂操作
     *
     * @param serviceClass
     * @param <T>
     * @return
     */
    public static <T> T getProxyService(Class<T> serviceClass) {
        Object o = Proxy.newProxyInstance(serviceClass.getClassLoader(),
                new Class[]{serviceClass}, new InvocationHandler() {
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        // 1. 将方法调用转换为消息对象
                        int sequenceId = SequenceIdGenerator.nextId();
                        RpcRequestMessage rpcRequestMessage = new RpcRequestMessage(
                                sequenceId,
                                serviceClass.getName(),
                                method.getName(),
                                method.getReturnType(),
                                method.getParameterTypes(),
                                args
                        );

                        // 2. 将消息对象发送出去
                        getChannel().writeAndFlush(rpcRequestMessage);

                        // 3. 准备一个Promise对象接收结果，并指定Promise异步接收结果的线程
                        DefaultPromise<Object> promise = new DefaultPromise(getChannel().eventLoop());
                        RpcResponseMessageHandler.PROMISE_MAP.put(sequenceId, promise);

                        // 这里可以调用sync()或者await()，
                        // 区别：sync()如果发生异常会打印异常，
                        // 而await()不会发生异常，不管是接收到的是数据还是异常都会返回，向下执行
                        promise.await();
                        if (promise.isSuccess()) {
                            // 调用正常
                            return promise.getNow();
                        } else {
                            // 调用失败
                            throw new RuntimeException(promise.cause());
                        }
                    }
                });
        return (T) o;
    }

    private static Channel channel;

    /**
     * 获取唯一的channel对象
     *
     * @return
     */
    public static Channel getChannel() {
        if (channel == null) {
            synchronized (RpcRequestMessageHandler.class) {
                if (channel == null) {
                    initChannel();
                }
            }
        }
        return channel;
    }

    private static void initChannel() {
        LoggingHandler loggingHandler = new LoggingHandler(LogLevel.DEBUG);
        MessageCodecSharable messageCodec = new MessageCodecSharable();
        RpcResponseMessageHandler rpcResponseMessageHandler = new RpcResponseMessageHandler();

        NioEventLoopGroup group = new NioEventLoopGroup();
        ChannelFuture channelFuture = null;
        try {
            channelFuture = new Bootstrap()
                    .group(group)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<NioSocketChannel>() {
                        @Override
                        protected void initChannel(NioSocketChannel ch) throws Exception {
                            ch.pipeline()
                                    .addLast(new ProtocolFrameDecoder())
                                    .addLast(loggingHandler)
                                    .addLast(messageCodec)
                                    .addLast(rpcResponseMessageHandler);
                        }
                    })
                    .connect("localhost", 8080).sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        // 这里不能使用事件监听的方式获取Channel，因为事件监听是异步的方式，
        // 会使得还没建立好连接，就把空的Channel返回了，所以必须同步等待连接建立好再返回
        channel = channelFuture.channel();
        log.debug("RPC客户端连接成功... {}" + channel);

        // 而NioEventGroup的关闭必须是异步的，防止阻塞住了主线程中的操作
        // 监听客户端SocketChannel关闭事件，关闭客户端事件循环组中的事件循环
        channel.closeFuture().addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                // 客户端关闭
                log.debug("客户端正在关闭...");
                group.shutdownGracefully();
                log.debug("客户端关闭成功！");
            }
        });
    }

    private RpcClientMgr() {
    }
}
